package com.example.mongoes.controller;

import com.anwen.mongo.annotation.transactional.MongoTransactional;
import com.anwen.mongo.bson.MongoPlusDocument;
import com.anwen.mongo.manager.MongoPlusClient;
import com.example.mongoes.entity.Job;
import com.example.mongoes.entity.User;
import com.example.mongoes.service.JobService;
import com.example.mongoes.service.UserService;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.Date;


@RestController
@RequestMapping("/mongo/test")
public class TextController {
    @Autowired
    private UserService userService;

    @Autowired
    private JobService jobService;

    @Autowired
    private MongoPlusClient mongoPlusclient;


    @PostMapping("/upload")
    public String aa(@RequestParam("file") MultipartFile file) throws Exception {
        MongoDatabase database = mongoPlusclient.getMongoDatabase("test");
        GridFSBucket gridFSBucket = GridFSBuckets.create(database, "myBucket");
        ObjectId objectId = gridFSBucket.uploadFromStream(file.getOriginalFilename(),
                file.getInputStream(),
                new GridFSUploadOptions().metadata(
                        new MongoPlusDocument()
                                .append("md5","12233").append("version","1")
                                .append("creator","wg").append("ct",new Date())
                ));

        return objectId.toHexString();
    }


    @PostMapping("/add")
   public boolean add() {
        User user = new User();
        user.setName("龙猫猫");
        user.setAge(20L);
        user.setEmail("1765742739@QQ.com");
        userService.saveOrUpdate(user);
        return true;
    }


    @PostMapping("/acid")
    @MongoTransactional
    public Boolean testACID() {
        User user = new User();
        user.setName("测试");
        user.setAge(20L);
        user.setEmail("123132@QQ.com");
        Job job = new Job();
        job.setName("测试job");
        job.setDescription("当个员工");
        userService.saveOrUpdate(user);
        job.setUserId(user.getId());
        jobService.saveOrUpdate(job);
        int i=1/0;
        return true;
    }
}
